home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / arm / cli / logPanel.py < prev    next >
Encoding:
Python Source  |  2012-05-18  |  50.3 KB  |  1,341 lines

  1. """
  2. Panel providing a chronological log of events its been configured to listen
  3. for. This provides prepopulation from the log file and supports filtering by
  4. regular expressions.
  5. """
  6.  
  7. import re
  8. import os
  9. import time
  10. import curses
  11. import threading
  12.  
  13. from TorCtl import TorCtl
  14.  
  15. import popups
  16. from version import VERSION
  17. from util import conf, log, panel, sysTools, torTools, uiTools
  18.  
  19. TOR_EVENT_TYPES = {
  20.   "d": "DEBUG",   "a": "ADDRMAP",          "k": "DESCCHANGED",  "s": "STREAM",
  21.   "i": "INFO",    "f": "AUTHDIR_NEWDESCS", "g": "GUARD",        "r": "STREAM_BW",
  22.   "n": "NOTICE",  "h": "BUILDTIMEOUT_SET", "l": "NEWCONSENSUS", "t": "STATUS_CLIENT",
  23.   "w": "WARN",    "b": "BW",               "m": "NEWDESC",      "u": "STATUS_GENERAL",
  24.   "e": "ERR",     "c": "CIRC",             "p": "NS",           "v": "STATUS_SERVER",
  25.                   "j": "CLIENTS_SEEN",     "q": "ORCONN"}
  26.  
  27. EVENT_LISTING = """        d DEBUG      a ADDRMAP           k DESCCHANGED   s STREAM
  28.         i INFO       f AUTHDIR_NEWDESCS  g GUARD         r STREAM_BW
  29.         n NOTICE     h BUILDTIMEOUT_SET  l NEWCONSENSUS  t STATUS_CLIENT
  30.         w WARN       b BW                m NEWDESC       u STATUS_GENERAL
  31.         e ERR        c CIRC              p NS            v STATUS_SERVER
  32.                      j CLIENTS_SEEN      q ORCONN
  33.           DINWE tor runlevel+            A All Events
  34.           12345 arm runlevel+            X No Events
  35.           67890 torctl runlevel+         U Unknown Events"""
  36.  
  37. RUNLEVEL_EVENT_COLOR = {log.DEBUG: "magenta", log.INFO: "blue", log.NOTICE: "green",
  38.                         log.WARN: "yellow", log.ERR: "red"}
  39. DAYBREAK_EVENT = "DAYBREAK" # special event for marking when the date changes
  40. TIMEZONE_OFFSET = time.altzone if time.localtime()[8] else time.timezone
  41.  
  42. ENTRY_INDENT = 2 # spaces an entry's message is indented after the first line
  43. DEFAULT_CONFIG = {"features.logFile": "",
  44.                   "features.log.showDateDividers": True,
  45.                   "features.log.showDuplicateEntries": False,
  46.                   "features.log.entryDuration": 7,
  47.                   "features.log.maxLinesPerEntry": 6,
  48.                   "features.log.prepopulate": True,
  49.                   "features.log.prepopulateReadLimit": 5000,
  50.                   "features.log.maxRefreshRate": 300,
  51.                   "features.log.regex": [],
  52.                   "cache.logPanel.size": 1000,
  53.                   "log.logPanel.prepopulateSuccess": log.INFO,
  54.                   "log.logPanel.prepopulateFailed": log.WARN,
  55.                   "log.logPanel.logFileOpened": log.NOTICE,
  56.                   "log.logPanel.logFileWriteFailed": log.ERR,
  57.                   "log.logPanel.forceDoubleRedraw": log.DEBUG,
  58.                   "log.configEntryTypeError": log.NOTICE}
  59.  
  60. DUPLICATE_MSG = " [%i duplicate%s hidden]"
  61.  
  62. # The height of the drawn content is estimated based on the last time we redrew
  63. # the panel. It's chiefly used for scrolling and the bar indicating its
  64. # position. Letting the estimate be too inaccurate results in a display bug, so
  65. # redraws the display if it's off by this threshold.
  66. CONTENT_HEIGHT_REDRAW_THRESHOLD = 3
  67.  
  68. # static starting portion of common log entries, fetched from the config when
  69. # needed if None
  70. COMMON_LOG_MESSAGES = None
  71.  
  72. # cached values and the arguments that generated it for the getDaybreaks and
  73. # getDuplicates functions
  74. CACHED_DAYBREAKS_ARGUMENTS = (None, None) # events, current day
  75. CACHED_DAYBREAKS_RESULT = None
  76. CACHED_DUPLICATES_ARGUMENTS = None # events
  77. CACHED_DUPLICATES_RESULT = None
  78.  
  79. # duration we'll wait for the deduplication function before giving up (in ms)
  80. DEDUPLICATION_TIMEOUT = 100
  81.  
  82. # maximum number of regex filters we'll remember
  83. MAX_REGEX_FILTERS = 5
  84.  
  85. def daysSince(timestamp=None):
  86.   """
  87.   Provides the number of days since the epoch converted to local time (rounded
  88.   down).
  89.   
  90.   Arguments:
  91.     timestamp - unix timestamp to convert, current time if undefined
  92.   """
  93.   
  94.   if timestamp == None: timestamp = time.time()
  95.   return int((timestamp - TIMEZONE_OFFSET) / 86400)
  96.  
  97. def expandEvents(eventAbbr):
  98.   """
  99.   Expands event abbreviations to their full names. Beside mappings provided in
  100.   TOR_EVENT_TYPES this recognizes the following special events and aliases:
  101.   U - UKNOWN events
  102.   A - all events
  103.   X - no events
  104.   DINWE - runlevel and higher
  105.   12345 - arm runlevel and higher (ARM_DEBUG - ARM_ERR)
  106.   67890 - torctl runlevel and higher (TORCTL_DEBUG - TORCTL_ERR)
  107.   Raises ValueError with invalid input if any part isn't recognized.
  108.   
  109.   Examples:
  110.   "inUt" -> ["INFO", "NOTICE", "UNKNOWN", "STREAM_BW"]
  111.   "N4" -> ["NOTICE", "WARN", "ERR", "ARM_WARN", "ARM_ERR"]
  112.   "cfX" -> []
  113.   
  114.   Arguments:
  115.     eventAbbr - flags to be parsed to event types
  116.   """
  117.   
  118.   expandedEvents, invalidFlags = set(), ""
  119.   
  120.   for flag in eventAbbr:
  121.     if flag == "A":
  122.       armRunlevels = ["ARM_" + runlevel for runlevel in log.Runlevel.values()]
  123.       torctlRunlevels = ["TORCTL_" + runlevel for runlevel in log.Runlevel.values()]
  124.       expandedEvents = set(TOR_EVENT_TYPES.values() + armRunlevels + torctlRunlevels + ["UNKNOWN"])
  125.       break
  126.     elif flag == "X":
  127.       expandedEvents = set()
  128.       break
  129.     elif flag in "DINWE1234567890":
  130.       # all events for a runlevel and higher
  131.       if flag in "DINWE": typePrefix = ""
  132.       elif flag in "12345": typePrefix = "ARM_"
  133.       elif flag in "67890": typePrefix = "TORCTL_"
  134.       
  135.       if flag in "D16": runlevelIndex = 0
  136.       elif flag in "I27": runlevelIndex = 1
  137.       elif flag in "N38": runlevelIndex = 2
  138.       elif flag in "W49": runlevelIndex = 3
  139.       elif flag in "E50": runlevelIndex = 4
  140.       
  141.       runlevelSet = [typePrefix + runlevel for runlevel in log.Runlevel.values()[runlevelIndex:]]
  142.       expandedEvents = expandedEvents.union(set(runlevelSet))
  143.     elif flag == "U":
  144.       expandedEvents.add("UNKNOWN")
  145.     elif flag in TOR_EVENT_TYPES:
  146.       expandedEvents.add(TOR_EVENT_TYPES[flag])
  147.     else:
  148.       invalidFlags += flag
  149.   
  150.   if invalidFlags: raise ValueError(invalidFlags)
  151.   else: return expandedEvents
  152.  
  153. def getMissingEventTypes():
  154.   """
  155.   Provides the event types the current torctl connection supports but arm
  156.   doesn't. This provides an empty list if no event types are missing, and None
  157.   if the GETINFO query fails.
  158.   """
  159.   
  160.   torEventTypes = torTools.getConn().getInfo("events/names")
  161.   
  162.   if torEventTypes:
  163.     torEventTypes = torEventTypes.split(" ")
  164.     armEventTypes = TOR_EVENT_TYPES.values()
  165.     return [event for event in torEventTypes if not event in armEventTypes]
  166.   else: return None # GETINFO call failed
  167.  
  168. def setEventListening(events):
  169.   """
  170.   Configures the events Tor listens for, filtering non-tor events from what we
  171.   request from the controller. This returns a sorted list of the events we
  172.   successfully set.
  173.   
  174.   Arguments:
  175.     events - event types to attempt to set
  176.   """
  177.   
  178.   events = set(events) # drops duplicates
  179.   torEvents = events.intersection(set(TOR_EVENT_TYPES.values()))
  180.   
  181.   # adds events unrecognized by arm if we're listening to the 'UNKNOWN' type
  182.   if "UNKNOWN" in events:
  183.     torEvents.update(set(getMissingEventTypes()))
  184.   
  185.   setEvents = torTools.getConn().setControllerEvents(list(torEvents))
  186.   
  187.   # provides back the input set minus events we failed to set
  188.   return sorted(events.difference(torTools.FAILED_EVENTS))
  189.  
  190. def loadLogMessages():
  191.   """
  192.   Fetches a mapping of common log messages to their runlevels from the config.
  193.   """
  194.   
  195.   global COMMON_LOG_MESSAGES
  196.   armConf = conf.getConfig("arm")
  197.   
  198.   COMMON_LOG_MESSAGES = {}
  199.   for confKey in armConf.getKeys():
  200.     if confKey.startswith("msg."):
  201.       eventType = confKey[4:].upper()
  202.       messages = armConf.get(confKey, [])
  203.       COMMON_LOG_MESSAGES[eventType] = messages
  204.  
  205. def getLogFileEntries(runlevels, readLimit = None, addLimit = None, config = None):
  206.   """
  207.   Parses tor's log file for past events matching the given runlevels, providing
  208.   a list of log entries (ordered newest to oldest). Limiting the number of read
  209.   entries is suggested to avoid parsing everything from logs in the GB and TB
  210.   range.
  211.   
  212.   Arguments:
  213.     runlevels - event types (DEBUG - ERR) to be returned
  214.     readLimit - max lines of the log file that'll be read (unlimited if None)
  215.     addLimit  - maximum entries to provide back (unlimited if None)
  216.     config    - configuration parameters related to this panel, uses defaults
  217.                 if left as None
  218.   """
  219.   
  220.   startTime = time.time()
  221.   if not runlevels: return []
  222.   
  223.   if not config: config = DEFAULT_CONFIG
  224.   
  225.   # checks tor's configuration for the log file's location (if any exists)
  226.   loggingTypes, loggingLocation = None, None
  227.   for loggingEntry in torTools.getConn().getOption("Log", [], True):
  228.     # looks for an entry like: notice file /var/log/tor/notices.log
  229.     entryComp = loggingEntry.split()
  230.     
  231.     if entryComp[1] == "file":
  232.       loggingTypes, loggingLocation = entryComp[0], entryComp[2]
  233.       break
  234.   
  235.   if not loggingLocation: return []
  236.   
  237.   # includes the prefix for tor paths
  238.   loggingLocation = torTools.getConn().getPathPrefix() + loggingLocation
  239.   
  240.   # if the runlevels argument is a superset of the log file then we can
  241.   # limit the read contents to the addLimit
  242.   runlevels = log.Runlevel.values()
  243.   loggingTypes = loggingTypes.upper()
  244.   if addLimit and (not readLimit or readLimit > addLimit):
  245.     if "-" in loggingTypes:
  246.       divIndex = loggingTypes.find("-")
  247.       sIndex = runlevels.index(loggingTypes[:divIndex])
  248.       eIndex = runlevels.index(loggingTypes[divIndex+1:])
  249.       logFileRunlevels = runlevels[sIndex:eIndex+1]
  250.     else:
  251.       sIndex = runlevels.index(loggingTypes)
  252.       logFileRunlevels = runlevels[sIndex:]
  253.     
  254.     # checks if runlevels we're reporting are a superset of the file's contents
  255.     isFileSubset = True
  256.     for runlevelType in logFileRunlevels:
  257.       if runlevelType not in runlevels:
  258.         isFileSubset = False
  259.         break
  260.     
  261.     if isFileSubset: readLimit = addLimit
  262.   
  263.   # tries opening the log file, cropping results to avoid choking on huge logs
  264.   lines = []
  265.   try:
  266.     if readLimit:
  267.       lines = sysTools.call("tail -n %i %s" % (readLimit, loggingLocation))
  268.       if not lines: raise IOError()
  269.     else:
  270.       logFile = open(loggingLocation, "r")
  271.       lines = logFile.readlines()
  272.       logFile.close()
  273.   except IOError:
  274.     msg = "Unable to read tor's log file: %s" % loggingLocation
  275.     log.log(config["log.logPanel.prepopulateFailed"], msg)
  276.   
  277.   if not lines: return []
  278.   
  279.   loggedEvents = []
  280.   currentUnixTime, currentLocalTime = time.time(), time.localtime()
  281.   for i in range(len(lines) - 1, -1, -1):
  282.     line = lines[i]
  283.     
  284.     # entries look like:
  285.     # Jul 15 18:29:48.806 [notice] Parsing GEOIP file.
  286.     lineComp = line.split()
  287.     
  288.     # Checks that we have all the components we expect. This could happen if
  289.     # we're either not parsing a tor log or in weird edge cases (like being
  290.     # out of disk space)
  291.     
  292.     if len(lineComp) < 4: continue
  293.     
  294.     eventType = lineComp[3][1:-1].upper()
  295.     
  296.     if eventType in runlevels:
  297.       # converts timestamp to unix time
  298.       timestamp = " ".join(lineComp[:3])
  299.       
  300.       # strips the decimal seconds
  301.       if "." in timestamp: timestamp = timestamp[:timestamp.find(".")]
  302.       
  303.       # Ignoring wday and yday since they aren't used.
  304.       #
  305.       # Pretend the year is 2012, because 2012 is a leap year, and parsing a
  306.       # date with strptime fails if Feb 29th is passed without a year that's
  307.       # actually a leap year. We can't just use the current year, because we
  308.       # might be parsing old logs which didn't get rotated.
  309.       #
  310.       # https://trac.torproject.org/projects/tor/ticket/5265
  311.       
  312.       timestamp = "2012 " + timestamp
  313.       eventTimeComp = list(time.strptime(timestamp, "%Y %b %d %H:%M:%S"))
  314.       eventTimeComp[8] = currentLocalTime.tm_isdst
  315.       eventTime = time.mktime(eventTimeComp) # converts local to unix time
  316.       
  317.       # The above is gonna be wrong if the logs are for the previous year. If
  318.       # the event's in the future then correct for this.
  319.       if eventTime > currentUnixTime + 60:
  320.         eventTimeComp[0] -= 1
  321.         eventTime = time.mktime(eventTimeComp)
  322.       
  323.       eventMsg = " ".join(lineComp[4:])
  324.       loggedEvents.append(LogEntry(eventTime, eventType, eventMsg, RUNLEVEL_EVENT_COLOR[eventType]))
  325.     
  326.     if "opening log file" in line:
  327.       break # this entry marks the start of this tor instance
  328.   
  329.   if addLimit: loggedEvents = loggedEvents[:addLimit]
  330.   msg = "Read %i entries from tor's log file: %s (read limit: %i, runtime: %0.3f)" % (len(loggedEvents), loggingLocation, readLimit, time.time() - startTime)
  331.   log.log(config["log.logPanel.prepopulateSuccess"], msg)
  332.   return loggedEvents
  333.  
  334. def getDaybreaks(events, ignoreTimeForCache = False):
  335.   """
  336.   Provides the input events back with special 'DAYBREAK_EVENT' markers inserted
  337.   whenever the date changed between log entries (or since the most recent
  338.   event). The timestamp matches the beginning of the day for the following
  339.   entry.
  340.   
  341.   Arguments:
  342.     events             - chronologically ordered listing of events
  343.     ignoreTimeForCache - skips taking the day into consideration for providing
  344.                          cached results if true
  345.   """
  346.   
  347.   global CACHED_DAYBREAKS_ARGUMENTS, CACHED_DAYBREAKS_RESULT
  348.   if not events: return []
  349.   
  350.   newListing = []
  351.   currentDay = daysSince()
  352.   lastDay = currentDay
  353.   
  354.   if CACHED_DAYBREAKS_ARGUMENTS[0] == events and \
  355.     (ignoreTimeForCache or CACHED_DAYBREAKS_ARGUMENTS[1] == currentDay):
  356.     return list(CACHED_DAYBREAKS_RESULT)
  357.   
  358.   for entry in events:
  359.     eventDay = daysSince(entry.timestamp)
  360.     if eventDay != lastDay:
  361.       markerTimestamp = (eventDay * 86400) + TIMEZONE_OFFSET
  362.       newListing.append(LogEntry(markerTimestamp, DAYBREAK_EVENT, "", "white"))
  363.     
  364.     newListing.append(entry)
  365.     lastDay = eventDay
  366.   
  367.   CACHED_DAYBREAKS_ARGUMENTS = (list(events), currentDay)
  368.   CACHED_DAYBREAKS_RESULT = list(newListing)
  369.   
  370.   return newListing
  371.  
  372. def getDuplicates(events):
  373.   """
  374.   Deduplicates a list of log entries, providing back a tuple listing with the
  375.   log entry and count of duplicates following it. Entries in different days are
  376.   not considered to be duplicates. This times out, returning None if it takes
  377.   longer than DEDUPLICATION_TIMEOUT.
  378.   
  379.   Arguments:
  380.     events - chronologically ordered listing of events
  381.   """
  382.   
  383.   global CACHED_DUPLICATES_ARGUMENTS, CACHED_DUPLICATES_RESULT
  384.   if CACHED_DUPLICATES_ARGUMENTS == events:
  385.     return list(CACHED_DUPLICATES_RESULT)
  386.   
  387.   # loads common log entries from the config if they haven't been
  388.   if COMMON_LOG_MESSAGES == None: loadLogMessages()
  389.   
  390.   startTime = time.time()
  391.   eventsRemaining = list(events)
  392.   returnEvents = []
  393.   
  394.   while eventsRemaining:
  395.     entry = eventsRemaining.pop(0)
  396.     duplicateIndices = isDuplicate(entry, eventsRemaining, True)
  397.     
  398.     # checks if the call timeout has been reached
  399.     if (time.time() - startTime) > DEDUPLICATION_TIMEOUT / 1000.0:
  400.       return None
  401.     
  402.     # drops duplicate entries
  403.     duplicateIndices.reverse()
  404.     for i in duplicateIndices: del eventsRemaining[i]
  405.     
  406.     returnEvents.append((entry, len(duplicateIndices)))
  407.   
  408.   CACHED_DUPLICATES_ARGUMENTS = list(events)
  409.   CACHED_DUPLICATES_RESULT = list(returnEvents)
  410.   
  411.   return returnEvents
  412.  
  413. def isDuplicate(event, eventSet, getDuplicates = False):
  414.   """
  415.   True if the event is a duplicate for something in the eventSet, false
  416.   otherwise. If the getDuplicates flag is set this provides the indices of
  417.   the duplicates instead.
  418.   
  419.   Arguments:
  420.     event         - event to search for duplicates of
  421.     eventSet      - set to look for the event in
  422.     getDuplicates - instead of providing back a boolean this gives a list of
  423.                     the duplicate indices in the eventSet
  424.   """
  425.   
  426.   duplicateIndices = []
  427.   for i in range(len(eventSet)):
  428.     forwardEntry = eventSet[i]
  429.     
  430.     # if showing dates then do duplicate detection for each day, rather
  431.     # than globally
  432.     if forwardEntry.type == DAYBREAK_EVENT: break
  433.     
  434.     if event.type == forwardEntry.type:
  435.       isDuplicate = False
  436.       if event.msg == forwardEntry.msg: isDuplicate = True
  437.       elif event.type in COMMON_LOG_MESSAGES:
  438.         for commonMsg in COMMON_LOG_MESSAGES[event.type]:
  439.           # if it starts with an asterisk then check the whole message rather
  440.           # than just the start
  441.           if commonMsg[0] == "*":
  442.             isDuplicate = commonMsg[1:] in event.msg and commonMsg[1:] in forwardEntry.msg
  443.           else:
  444.             isDuplicate = event.msg.startswith(commonMsg) and forwardEntry.msg.startswith(commonMsg)
  445.           
  446.           if isDuplicate: break
  447.       
  448.       if isDuplicate:
  449.         if getDuplicates: duplicateIndices.append(i)
  450.         else: return True
  451.   
  452.   if getDuplicates: return duplicateIndices
  453.   else: return False
  454.  
  455. class LogEntry():
  456.   """
  457.   Individual log file entry, having the following attributes:
  458.     timestamp - unix timestamp for when the event occurred
  459.     eventType - event type that occurred ("INFO", "BW", "ARM_WARN", etc)
  460.     msg       - message that was logged
  461.     color     - color of the log entry
  462.   """
  463.   
  464.   def __init__(self, timestamp, eventType, msg, color):
  465.     self.timestamp = timestamp
  466.     self.type = eventType
  467.     self.msg = msg
  468.     self.color = color
  469.     self._displayMessage = None
  470.   
  471.   def getDisplayMessage(self, includeDate = False):
  472.     """
  473.     Provides the entry's message for the log.
  474.     
  475.     Arguments:
  476.       includeDate - appends the event's date to the start of the message
  477.     """
  478.     
  479.     if includeDate:
  480.       # not the common case so skip caching
  481.       entryTime = time.localtime(self.timestamp)
  482.       timeLabel =  "%i/%i/%i %02i:%02i:%02i" % (entryTime[1], entryTime[2], entryTime[0], entryTime[3], entryTime[4], entryTime[5])
  483.       return "%s [%s] %s" % (timeLabel, self.type, self.msg)
  484.     
  485.     if not self._displayMessage:
  486.       entryTime = time.localtime(self.timestamp)
  487.       self._displayMessage = "%02i:%02i:%02i [%s] %s" % (entryTime[3], entryTime[4], entryTime[5], self.type, self.msg)
  488.     
  489.     return self._displayMessage
  490.  
  491. class TorEventObserver(TorCtl.PostEventListener):
  492.   """
  493.   Listens for all types of events provided by TorCtl, providing an LogEntry
  494.   instance to the given callback function.
  495.   """
  496.   
  497.   def __init__(self, callback):
  498.     """
  499.     Tor event listener with the purpose of translating events to nicely
  500.     formatted calls of a callback function.
  501.     
  502.     Arguments:
  503.       callback - function accepting a LogEntry, called when an event of these
  504.                  types occur
  505.     """
  506.     
  507.     TorCtl.PostEventListener.__init__(self)
  508.     self.callback = callback
  509.   
  510.   def circ_status_event(self, event):
  511.     msg = "ID: %-3s STATUS: %-10s PATH: %s" % (event.circ_id, event.status, ", ".join(event.path))
  512.     if event.purpose: msg += " PURPOSE: %s" % event.purpose
  513.     if event.reason: msg += " REASON: %s" % event.reason
  514.     if event.remote_reason: msg += " REMOTE_REASON: %s" % event.remote_reason
  515.     self._notify(event, msg, "yellow")
  516.   
  517.   def buildtimeout_set_event(self, event):
  518.     self._notify(event, "SET_TYPE: %s, TOTAL_TIMES: %s, TIMEOUT_MS: %s, XM: %s, ALPHA: %s, CUTOFF_QUANTILE: %s" % (event.set_type, event.total_times, event.timeout_ms, event.xm, event.alpha, event.cutoff_quantile))
  519.   
  520.   def stream_status_event(self, event):
  521.     self._notify(event, "ID: %s STATUS: %s CIRC_ID: %s TARGET: %s:%s REASON: %s REMOTE_REASON: %s SOURCE: %s SOURCE_ADDR: %s PURPOSE: %s" % (event.strm_id, event.status, event.circ_id, event.target_host, event.target_port, event.reason, event.remote_reason, event.source, event.source_addr, event.purpose))
  522.   
  523.   def or_conn_status_event(self, event):
  524.     msg = "STATUS: %-10s ENDPOINT: %-20s" % (event.status, event.endpoint)
  525.     if event.reason: msg += " REASON: %-6s" % event.reason
  526.     if event.ncircs: msg += " NCIRCS: %i" % event.ncircs
  527.     self._notify(event, msg)
  528.   
  529.   def stream_bw_event(self, event):
  530.     self._notify(event, "ID: %s READ: %s WRITTEN: %s" % (event.strm_id, event.bytes_read, event.bytes_written))
  531.   
  532.   def bandwidth_event(self, event):
  533.     self._notify(event, "READ: %i, WRITTEN: %i" % (event.read, event.written), "cyan")
  534.   
  535.   def msg_event(self, event):
  536.     self._notify(event, event.msg, RUNLEVEL_EVENT_COLOR[event.level])
  537.   
  538.   def new_desc_event(self, event):
  539.     idlistStr = [str(item) for item in event.idlist]
  540.     self._notify(event, ", ".join(idlistStr))
  541.   
  542.   def address_mapped_event(self, event):
  543.     whenLabel, gmtExpiryLabel = "", ""
  544.     
  545.     if event.when:
  546.       whenLabel = time.strftime("%H:%M %m/%d/%Y", event.when)
  547.     
  548.     # TODO: torctl is getting an 'error' and 'gmt_expiry' attribute so display
  549.     # those when they become available
  550.     #
  551.     #if event.gmt_expiry:
  552.     #  gmtExpiryLabel = time.strftime("%H:%M %m/%d/%Y", event.gmt_expiry)
  553.     
  554.     self._notify(event, "%s, %s -> %s" % (whenLabel, event.from_addr, event.to_addr))
  555.   
  556.   def ns_event(self, event):
  557.     # NetworkStatus params: nickname, idhash, orhash, ip, orport (int),
  558.     #     dirport (int), flags, idhex, bandwidth, updated (datetime)
  559.     msg = ", ".join(["%s (%s)" % (ns.idhex, ns.nickname) for ns in event.nslist])
  560.     self._notify(event, "Listed (%i): %s" % (len(event.nslist), msg), "blue")
  561.   
  562.   def new_consensus_event(self, event):
  563.     msg = ", ".join(["%s (%s)" % (ns.idhex, ns.nickname) for ns in event.nslist])
  564.     self._notify(event, "Listed (%i): %s" % (len(event.nslist), msg), "magenta")
  565.   
  566.   def guard_event(self, event):
  567.     msg = "%s (%s), STATUS: %s" % (event.idhex, event.nick, event.status)
  568.     self._notify(event, msg, "yellow")
  569.   
  570.   def unknown_event(self, event):
  571.     msg = "(%s) %s" % (event.event_name, event.event_string)
  572.     self.callback(LogEntry(event.arrived_at, "UNKNOWN", msg, "red"))
  573.   
  574.   def _notify(self, event, msg, color="white"):
  575.     self.callback(LogEntry(event.arrived_at, event.event_name, msg, color))
  576.  
  577. class LogPanel(panel.Panel, threading.Thread):
  578.   """
  579.   Listens for and displays tor, arm, and torctl events. This can prepopulate
  580.   from tor's log file if it exists.
  581.   """
  582.   
  583.   def __init__(self, stdscr, loggedEvents, config=None):
  584.     panel.Panel.__init__(self, stdscr, "log", 0)
  585.     threading.Thread.__init__(self)
  586.     self.setDaemon(True)
  587.     
  588.     # Make sure that the msg.* messages are loaded. Lazy loading it later is
  589.     # fine, but this way we're sure it happens before warning about unused
  590.     # config options.
  591.     loadLogMessages()
  592.     
  593.     # regex filters the user has defined
  594.     self.filterOptions = []
  595.     
  596.     self._config = dict(DEFAULT_CONFIG)
  597.     
  598.     if config:
  599.       config.update(self._config, {
  600.         "features.log.maxLinesPerEntry": 1,
  601.         "features.log.prepopulateReadLimit": 0,
  602.         "features.log.maxRefreshRate": 10,
  603.         "cache.logPanel.size": 1000})
  604.       
  605.       for filter in self._config["features.log.regex"]:
  606.         # checks if we can't have more filters
  607.         if len(self.filterOptions) >= MAX_REGEX_FILTERS: break
  608.         
  609.         try:
  610.           re.compile(filter)
  611.           self.filterOptions.append(filter)
  612.         except re.error, exc:
  613.           msg = "Invalid regular expression pattern (%s): %s" % (exc, filter)
  614.           log.log(self._config["log.configEntryTypeError"], msg)
  615.     
  616.     # collapses duplicate log entries if false, showing only the most recent
  617.     self.showDuplicates = self._config["features.log.showDuplicateEntries"]
  618.     
  619.     # restricts the input to the set of events we can listen to, and
  620.     # configures the controller to liten to them
  621.     loggedEvents = setEventListening(loggedEvents)
  622.     
  623.     self.setPauseAttr("msgLog")         # tracks the message log when we're paused
  624.     self.msgLog = []                    # log entries, sorted by the timestamp
  625.     self.loggedEvents = loggedEvents    # events we're listening to
  626.     self.regexFilter = None             # filter for presented log events (no filtering if None)
  627.     self.lastContentHeight = 0          # height of the rendered content when last drawn
  628.     self.logFile = None                 # file log messages are saved to (skipped if None)
  629.     self.scroll = 0
  630.     
  631.     self._lastUpdate = -1               # time the content was last revised
  632.     self._halt = False                  # terminates thread if true
  633.     self._cond = threading.Condition()  # used for pausing/resuming the thread
  634.     
  635.     # restricts concurrent write access to attributes used to draw the display
  636.     # and pausing:
  637.     # msgLog, loggedEvents, regexFilter, scroll
  638.     self.valsLock = threading.RLock()
  639.     
  640.     # cached parameters (invalidated if arguments for them change)
  641.     # last set of events we've drawn with
  642.     self._lastLoggedEvents = []
  643.     
  644.     # _getTitle (args: loggedEvents, regexFilter pattern, width)
  645.     self._titleCache = None
  646.     self._titleArgs = (None, None, None)
  647.     
  648.     # adds arm listener and prepopulates log with past tor/arm events
  649.     log.LOG_LOCK.acquire()
  650.     try:
  651.       log.addListeners(log.Runlevel.values(), self._registerArmEvent)
  652.       self.reprepopulateEvents()
  653.     finally:
  654.       log.LOG_LOCK.release()
  655.     
  656.     # leaving lastContentHeight as being too low causes initialization problems
  657.     self.lastContentHeight = len(self.msgLog)
  658.     
  659.     # adds listeners for tor and torctl events
  660.     conn = torTools.getConn()
  661.     conn.addEventListener(TorEventObserver(self.registerEvent))
  662.     conn.addTorCtlListener(self._registerTorCtlEvent)
  663.     conn.addStatusListener(self._resetListener)
  664.     
  665.     # opens log file if we'll be saving entries
  666.     if self._config["features.logFile"]:
  667.       logPath = self._config["features.logFile"]
  668.       
  669.       try:
  670.         # make dir if the path doesn't already exist
  671.         baseDir = os.path.dirname(logPath)
  672.         if not os.path.exists(baseDir): os.makedirs(baseDir)
  673.         
  674.         self.logFile = open(logPath, "a")
  675.         log.log(self._config["log.logPanel.logFileOpened"], "arm %s opening log file (%s)" % (VERSION, logPath))
  676.       except (IOError, OSError), exc:
  677.         log.log(self._config["log.logPanel.logFileWriteFailed"], "Unable to write to log file: %s" % sysTools.getFileErrorMsg(exc))
  678.         self.logFile = None
  679.   
  680.   def reprepopulateEvents(self):
  681.     """
  682.     Clears the event log and repopulates it from the arm and tor backlogs.
  683.     """
  684.     
  685.     self.valsLock.acquire()
  686.     
  687.     # clears the event log
  688.     self.msgLog = []
  689.     
  690.     # fetches past tor events from log file, if available
  691.     torEventBacklog = []
  692.     if self._config["features.log.prepopulate"]:
  693.       setRunlevels = list(set.intersection(set(self.loggedEvents), set(log.Runlevel.values())))
  694.       readLimit = self._config["features.log.prepopulateReadLimit"]
  695.       addLimit = self._config["cache.logPanel.size"]
  696.       torEventBacklog = getLogFileEntries(setRunlevels, readLimit, addLimit, self._config)
  697.     
  698.     # gets the set of arm events we're logging
  699.     setRunlevels = []
  700.     armRunlevels = log.Runlevel.values()
  701.     for i in range(len(armRunlevels)):
  702.       if "ARM_" + log.Runlevel.values()[i] in self.loggedEvents:
  703.         setRunlevels.append(armRunlevels[i])
  704.     
  705.     armEventBacklog = []
  706.     for level, msg, eventTime in log._getEntries(setRunlevels):
  707.       armEventEntry = LogEntry(eventTime, "ARM_" + level, msg, RUNLEVEL_EVENT_COLOR[level])
  708.       armEventBacklog.insert(0, armEventEntry)
  709.     
  710.     # joins armEventBacklog and torEventBacklog chronologically into msgLog
  711.     while armEventBacklog or torEventBacklog:
  712.       if not armEventBacklog:
  713.         self.msgLog.append(torEventBacklog.pop(0))
  714.       elif not torEventBacklog:
  715.         self.msgLog.append(armEventBacklog.pop(0))
  716.       elif armEventBacklog[0].timestamp < torEventBacklog[0].timestamp:
  717.         self.msgLog.append(torEventBacklog.pop(0))
  718.       else:
  719.         self.msgLog.append(armEventBacklog.pop(0))
  720.     
  721.     # crops events that are either too old, or more numerous than the caching size
  722.     self._trimEvents(self.msgLog)
  723.     
  724.     self.valsLock.release()
  725.   
  726.   def setDuplicateVisability(self, isVisible):
  727.     """
  728.     Sets if duplicate log entries are collaped or expanded.
  729.     
  730.     Arguments:
  731.       isVisible - if true all log entries are shown, otherwise they're
  732.                   deduplicated
  733.     """
  734.     
  735.     self.showDuplicates = isVisible
  736.   
  737.   def registerEvent(self, event):
  738.     """
  739.     Notes event and redraws log. If paused it's held in a temporary buffer.
  740.     
  741.     Arguments:
  742.       event - LogEntry for the event that occurred
  743.     """
  744.     
  745.     if not event.type in self.loggedEvents: return
  746.     
  747.     # strips control characters to avoid screwing up the terminal
  748.     event.msg = uiTools.getPrintable(event.msg)
  749.     
  750.     # note event in the log file if we're saving them
  751.     if self.logFile:
  752.       try:
  753.         self.logFile.write(event.getDisplayMessage(True) + "\n")
  754.         self.logFile.flush()
  755.       except IOError, exc:
  756.         log.log(self._config["log.logPanel.logFileWriteFailed"], "Unable to write to log file: %s" % sysTools.getFileErrorMsg(exc))
  757.         self.logFile = None
  758.     
  759.     self.valsLock.acquire()
  760.     self.msgLog.insert(0, event)
  761.     self._trimEvents(self.msgLog)
  762.     
  763.     # notifies the display that it has new content
  764.     if not self.regexFilter or self.regexFilter.search(event.getDisplayMessage()):
  765.       self._cond.acquire()
  766.       self._cond.notifyAll()
  767.       self._cond.release()
  768.     
  769.     self.valsLock.release()
  770.   
  771.   def _registerArmEvent(self, level, msg, eventTime):
  772.     eventColor = RUNLEVEL_EVENT_COLOR[level]
  773.     self.registerEvent(LogEntry(eventTime, "ARM_%s" % level, msg, eventColor))
  774.   
  775.   def _registerTorCtlEvent(self, level, msg):
  776.     eventColor = RUNLEVEL_EVENT_COLOR[level]
  777.     self.registerEvent(LogEntry(time.time(), "TORCTL_%s" % level, msg, eventColor))
  778.   
  779.   def setLoggedEvents(self, eventTypes):
  780.     """
  781.     Sets the event types recognized by the panel.
  782.     
  783.     Arguments:
  784.       eventTypes - event types to be logged
  785.     """
  786.     
  787.     if eventTypes == self.loggedEvents: return
  788.     self.valsLock.acquire()
  789.     
  790.     # configures the controller to listen for these tor events, and provides
  791.     # back a subset without anything we're failing to listen to
  792.     setTypes = setEventListening(eventTypes)
  793.     self.loggedEvents = setTypes
  794.     self.redraw(True)
  795.     self.valsLock.release()
  796.   
  797.   def getFilter(self):
  798.     """
  799.     Provides our currently selected regex filter.
  800.     """
  801.     
  802.     return self.filterOptions[0] if self.regexFilter else None
  803.   
  804.   def setFilter(self, logFilter):
  805.     """
  806.     Filters log entries according to the given regular expression.
  807.     
  808.     Arguments:
  809.       logFilter - regular expression used to determine which messages are
  810.                   shown, None if no filter should be applied
  811.     """
  812.     
  813.     if logFilter == self.regexFilter: return
  814.     
  815.     self.valsLock.acquire()
  816.     self.regexFilter = logFilter
  817.     self.redraw(True)
  818.     self.valsLock.release()
  819.   
  820.   def makeFilterSelection(self, selectedOption):
  821.     """
  822.     Makes the given filter selection, applying it to the log and reorganizing
  823.     our filter selection.
  824.     
  825.     Arguments:
  826.       selectedOption - regex filter we've already added, None if no filter
  827.                        should be applied
  828.     """
  829.     
  830.     if selectedOption:
  831.       try:
  832.         self.setFilter(re.compile(selectedOption))
  833.         
  834.         # move selection to top
  835.         self.filterOptions.remove(selectedOption)
  836.         self.filterOptions.insert(0, selectedOption)
  837.       except re.error, exc:
  838.         # shouldn't happen since we've already checked validity
  839.         msg = "Invalid regular expression ('%s': %s) - removing from listing" % (selectedOption, exc)
  840.         log.log(log.WARN, msg)
  841.         self.filterOptions.remove(selectedOption)
  842.     else: self.setFilter(None)
  843.   
  844.   def showFilterPrompt(self):
  845.     """
  846.     Prompts the user to add a new regex filter.
  847.     """
  848.     
  849.     regexInput = popups.inputPrompt("Regular expression: ")
  850.     
  851.     if regexInput:
  852.       try:
  853.         self.setFilter(re.compile(regexInput))
  854.         if regexInput in self.filterOptions: self.filterOptions.remove(regexInput)
  855.         self.filterOptions.insert(0, regexInput)
  856.       except re.error, exc:
  857.         popups.showMsg("Unable to compile expression: %s" % exc, 2)
  858.   
  859.   def showEventSelectionPrompt(self):
  860.     """
  861.     Prompts the user to select the events being listened for.
  862.     """
  863.     
  864.     # allow user to enter new types of events to log - unchanged if left blank
  865.     popup, width, height = popups.init(11, 80)
  866.     
  867.     if popup:
  868.       try:
  869.         # displays the available flags
  870.         popup.win.box()
  871.         popup.addstr(0, 0, "Event Types:", curses.A_STANDOUT)
  872.         eventLines = EVENT_LISTING.split("\n")
  873.         
  874.         for i in range(len(eventLines)):
  875.           popup.addstr(i + 1, 1, eventLines[i][6:])
  876.         
  877.         popup.win.refresh()
  878.         
  879.         userInput = popups.inputPrompt("Events to log: ")
  880.         if userInput:
  881.           userInput = userInput.replace(' ', '') # strips spaces
  882.           try: self.setLoggedEvents(expandEvents(userInput))
  883.           except ValueError, exc:
  884.             popups.showMsg("Invalid flags: %s" % str(exc), 2)
  885.       finally: popups.finalize()
  886.   
  887.   def showSnapshotPrompt(self):
  888.     """
  889.     Lets user enter a path to take a snapshot, canceling if left blank.
  890.     """
  891.     
  892.     pathInput = popups.inputPrompt("Path to save log snapshot: ")
  893.     
  894.     if pathInput:
  895.       try:
  896.         self.saveSnapshot(pathInput)
  897.         popups.showMsg("Saved: %s" % pathInput, 2)
  898.       except IOError, exc:
  899.         popups.showMsg("Unable to save snapshot: %s" % sysTools.getFileErrorMsg(exc), 2)
  900.   
  901.   def clear(self):
  902.     """
  903.     Clears the contents of the event log.
  904.     """
  905.     
  906.     self.valsLock.acquire()
  907.     self.msgLog = []
  908.     self.redraw(True)
  909.     self.valsLock.release()
  910.   
  911.   def saveSnapshot(self, path):
  912.     """
  913.     Saves the log events currently being displayed to the given path. This
  914.     takes filers into account. This overwrites the file if it already exists,
  915.     and raises an IOError if there's a problem.
  916.     
  917.     Arguments:
  918.       path - path where to save the log snapshot
  919.     """
  920.     
  921.     path = os.path.abspath(path)
  922.     
  923.     # make dir if the path doesn't already exist
  924.     baseDir = os.path.dirname(path)
  925.     
  926.     try:
  927.       if not os.path.exists(baseDir): os.makedirs(baseDir)
  928.     except OSError, exc:
  929.       raise IOError("unable to make directory '%s'" % baseDir)
  930.     
  931.     snapshotFile = open(path, "w")
  932.     self.valsLock.acquire()
  933.     try:
  934.       for entry in self.msgLog:
  935.         isVisible = not self.regexFilter or self.regexFilter.search(entry.getDisplayMessage())
  936.         if isVisible: snapshotFile.write(entry.getDisplayMessage(True) + "\n")
  937.       
  938.       self.valsLock.release()
  939.     except Exception, exc:
  940.       self.valsLock.release()
  941.       raise exc
  942.   
  943.   def handleKey(self, key):
  944.     isKeystrokeConsumed = True
  945.     if uiTools.isScrollKey(key):
  946.       pageHeight = self.getPreferredSize()[0] - 1
  947.       newScroll = uiTools.getScrollPosition(key, self.scroll, pageHeight, self.lastContentHeight)
  948.       
  949.       if self.scroll != newScroll:
  950.         self.valsLock.acquire()
  951.         self.scroll = newScroll
  952.         self.redraw(True)
  953.         self.valsLock.release()
  954.     elif key in (ord('u'), ord('U')):
  955.       self.valsLock.acquire()
  956.       self.showDuplicates = not self.showDuplicates
  957.       self.redraw(True)
  958.       self.valsLock.release()
  959.     elif key == ord('c') or key == ord('C'):
  960.       msg = "This will clear the log. Are you sure (c again to confirm)?"
  961.       keyPress = popups.showMsg(msg, attr = curses.A_BOLD)
  962.       if keyPress in (ord('c'), ord('C')): self.clear()
  963.     elif key == ord('f') or key == ord('F'):
  964.       # Provides menu to pick regular expression filters or adding new ones:
  965.       # for syntax see: http://docs.python.org/library/re.html#regular-expression-syntax
  966.       options = ["None"] + self.filterOptions + ["New..."]
  967.       oldSelection = 0 if not self.regexFilter else 1
  968.       
  969.       # does all activity under a curses lock to prevent redraws when adding
  970.       # new filters
  971.       panel.CURSES_LOCK.acquire()
  972.       try:
  973.         selection = popups.showMenu("Log Filter:", options, oldSelection)
  974.         
  975.         # applies new setting
  976.         if selection == 0:
  977.           self.setFilter(None)
  978.         elif selection == len(options) - 1:
  979.           # selected 'New...' option - prompt user to input regular expression
  980.           self.showFilterPrompt()
  981.         elif selection != -1:
  982.           self.makeFilterSelection(self.filterOptions[selection - 1])
  983.       finally:
  984.         panel.CURSES_LOCK.release()
  985.       
  986.       if len(self.filterOptions) > MAX_REGEX_FILTERS: del self.filterOptions[MAX_REGEX_FILTERS:]
  987.     elif key == ord('e') or key == ord('E'):
  988.       self.showEventSelectionPrompt()
  989.     elif key == ord('a') or key == ord('A'):
  990.       self.showSnapshotPrompt()
  991.     else: isKeystrokeConsumed = False
  992.     
  993.     return isKeystrokeConsumed
  994.   
  995.   def getHelp(self):
  996.     options = []
  997.     options.append(("up arrow", "scroll log up a line", None))
  998.     options.append(("down arrow", "scroll log down a line", None))
  999.     options.append(("a", "save snapshot of the log", None))
  1000.     options.append(("e", "change logged events", None))
  1001.     options.append(("f", "log regex filter", "enabled" if self.regexFilter else "disabled"))
  1002.     options.append(("u", "duplicate log entries", "visible" if self.showDuplicates else "hidden"))
  1003.     options.append(("c", "clear event log", None))
  1004.     return options
  1005.   
  1006.   def draw(self, width, height):
  1007.     """
  1008.     Redraws message log. Entries stretch to use available space and may
  1009.     contain up to two lines. Starts with newest entries.
  1010.     """
  1011.     
  1012.     currentLog = self.getAttr("msgLog")
  1013.     
  1014.     self.valsLock.acquire()
  1015.     self._lastLoggedEvents, self._lastUpdate = list(currentLog), time.time()
  1016.     
  1017.     # draws the top label
  1018.     if self.isTitleVisible():
  1019.       self.addstr(0, 0, self._getTitle(width), curses.A_STANDOUT)
  1020.     
  1021.     # restricts scroll location to valid bounds
  1022.     self.scroll = max(0, min(self.scroll, self.lastContentHeight - height + 1))
  1023.     
  1024.     # draws left-hand scroll bar if content's longer than the height
  1025.     msgIndent, dividerIndent = 1, 0 # offsets for scroll bar
  1026.     isScrollBarVisible = self.lastContentHeight > height - 1
  1027.     if isScrollBarVisible:
  1028.       msgIndent, dividerIndent = 3, 2
  1029.       self.addScrollBar(self.scroll, self.scroll + height - 1, self.lastContentHeight, 1)
  1030.     
  1031.     # draws log entries
  1032.     lineCount = 1 - self.scroll
  1033.     seenFirstDateDivider = False
  1034.     dividerAttr, duplicateAttr = curses.A_BOLD | uiTools.getColor("yellow"), curses.A_BOLD | uiTools.getColor("green")
  1035.     
  1036.     isDatesShown = self.regexFilter == None and self._config["features.log.showDateDividers"]
  1037.     eventLog = getDaybreaks(currentLog, self.isPaused()) if isDatesShown else list(currentLog)
  1038.     if not self.showDuplicates:
  1039.       deduplicatedLog = getDuplicates(eventLog)
  1040.       
  1041.       if deduplicatedLog == None:
  1042.         msg = "Deduplication took too long. Its current implementation has difficulty handling large logs so disabling it to keep the interface responsive."
  1043.         log.log(log.WARN, msg)
  1044.         self.showDuplicates = True
  1045.         deduplicatedLog = [(entry, 0) for entry in eventLog]
  1046.     else: deduplicatedLog = [(entry, 0) for entry in eventLog]
  1047.     
  1048.     # determines if we have the minimum width to show date dividers
  1049.     showDaybreaks = width - dividerIndent >= 3
  1050.     
  1051.     while deduplicatedLog:
  1052.       entry, duplicateCount = deduplicatedLog.pop(0)
  1053.       
  1054.       if self.regexFilter and not self.regexFilter.search(entry.getDisplayMessage()):
  1055.         continue  # filter doesn't match log message - skip
  1056.       
  1057.       # checks if we should be showing a divider with the date
  1058.       if entry.type == DAYBREAK_EVENT:
  1059.         # bottom of the divider
  1060.         if seenFirstDateDivider:
  1061.           if lineCount >= 1 and lineCount < height and showDaybreaks:
  1062.             self.addch(lineCount, dividerIndent, curses.ACS_LLCORNER,  dividerAttr)
  1063.             self.hline(lineCount, dividerIndent + 1, width - dividerIndent - 2, dividerAttr)
  1064.             self.addch(lineCount, width - 1, curses.ACS_LRCORNER, dividerAttr)
  1065.           
  1066.           lineCount += 1
  1067.         
  1068.         # top of the divider
  1069.         if lineCount >= 1 and lineCount < height and showDaybreaks:
  1070.           timeLabel = time.strftime(" %B %d, %Y ", time.localtime(entry.timestamp))
  1071.           self.addch(lineCount, dividerIndent, curses.ACS_ULCORNER, dividerAttr)
  1072.           self.addch(lineCount, dividerIndent + 1, curses.ACS_HLINE, dividerAttr)
  1073.           self.addstr(lineCount, dividerIndent + 2, timeLabel, curses.A_BOLD | dividerAttr)
  1074.           
  1075.           lineLength = width - dividerIndent - len(timeLabel) - 3
  1076.           self.hline(lineCount, dividerIndent + len(timeLabel) + 2, lineLength, dividerAttr)
  1077.           self.addch(lineCount, dividerIndent + len(timeLabel) + 2 + lineLength, curses.ACS_URCORNER, dividerAttr)
  1078.         
  1079.         seenFirstDateDivider = True
  1080.         lineCount += 1
  1081.       else:
  1082.         # entry contents to be displayed, tuples of the form:
  1083.         # (msg, formatting, includeLinebreak)
  1084.         displayQueue = []
  1085.         
  1086.         msgComp = entry.getDisplayMessage().split("\n")
  1087.         for i in range(len(msgComp)):
  1088.           font = curses.A_BOLD if "ERR" in entry.type else curses.A_NORMAL # emphasizes ERR messages
  1089.           displayQueue.append((msgComp[i].strip(), font | uiTools.getColor(entry.color), i != len(msgComp) - 1))
  1090.         
  1091.         if duplicateCount:
  1092.           pluralLabel = "s" if duplicateCount > 1 else ""
  1093.           duplicateMsg = DUPLICATE_MSG % (duplicateCount, pluralLabel)
  1094.           displayQueue.append((duplicateMsg, duplicateAttr, False))
  1095.         
  1096.         cursorLoc, lineOffset = msgIndent, 0
  1097.         maxEntriesPerLine = self._config["features.log.maxLinesPerEntry"]
  1098.         while displayQueue:
  1099.           msg, format, includeBreak = displayQueue.pop(0)
  1100.           drawLine = lineCount + lineOffset
  1101.           if lineOffset == maxEntriesPerLine: break
  1102.           
  1103.           maxMsgSize = width - cursorLoc - 1
  1104.           if len(msg) > maxMsgSize:
  1105.             # message is too long - break it up
  1106.             if lineOffset == maxEntriesPerLine - 1:
  1107.               msg = uiTools.cropStr(msg, maxMsgSize)
  1108.             else:
  1109.               msg, remainder = uiTools.cropStr(msg, maxMsgSize, 4, 4, uiTools.Ending.HYPHEN, True)
  1110.               displayQueue.insert(0, (remainder.strip(), format, includeBreak))
  1111.             
  1112.             includeBreak = True
  1113.           
  1114.           if drawLine < height and drawLine >= 1:
  1115.             if seenFirstDateDivider and width - dividerIndent >= 3 and showDaybreaks:
  1116.               self.addch(drawLine, dividerIndent, curses.ACS_VLINE, dividerAttr)
  1117.               self.addch(drawLine, width - 1, curses.ACS_VLINE, dividerAttr)
  1118.             
  1119.             self.addstr(drawLine, cursorLoc, msg, format)
  1120.           
  1121.           cursorLoc += len(msg)
  1122.           
  1123.           if includeBreak or not displayQueue:
  1124.             lineOffset += 1
  1125.             cursorLoc = msgIndent + ENTRY_INDENT
  1126.         
  1127.         lineCount += lineOffset
  1128.       
  1129.       # if this is the last line and there's room, then draw the bottom of the divider
  1130.       if not deduplicatedLog and seenFirstDateDivider:
  1131.         if lineCount < height and showDaybreaks:
  1132.           self.addch(lineCount, dividerIndent, curses.ACS_LLCORNER, dividerAttr)
  1133.           self.hline(lineCount, dividerIndent + 1, width - dividerIndent - 2, dividerAttr)
  1134.           self.addch(lineCount, width - 1, curses.ACS_LRCORNER, dividerAttr)
  1135.         
  1136.         lineCount += 1
  1137.     
  1138.     # redraw the display if...
  1139.     # - lastContentHeight was off by too much
  1140.     # - we're off the bottom of the page
  1141.     newContentHeight = lineCount + self.scroll - 1
  1142.     contentHeightDelta = abs(self.lastContentHeight - newContentHeight)
  1143.     forceRedraw, forceRedrawReason = True, ""
  1144.     
  1145.     if contentHeightDelta >= CONTENT_HEIGHT_REDRAW_THRESHOLD:
  1146.       forceRedrawReason = "estimate was off by %i" % contentHeightDelta
  1147.     elif newContentHeight > height and self.scroll + height - 1 > newContentHeight:
  1148.       forceRedrawReason = "scrolled off the bottom of the page"
  1149.     elif not isScrollBarVisible and newContentHeight > height - 1:
  1150.       forceRedrawReason = "scroll bar wasn't previously visible"
  1151.     elif isScrollBarVisible and newContentHeight <= height - 1:
  1152.       forceRedrawReason = "scroll bar shouldn't be visible"
  1153.     else: forceRedraw = False
  1154.     
  1155.     self.lastContentHeight = newContentHeight
  1156.     if forceRedraw:
  1157.       forceRedrawReason = "redrawing the log panel with the corrected content height (%s)" % forceRedrawReason
  1158.       log.log(self._config["log.logPanel.forceDoubleRedraw"], forceRedrawReason)
  1159.       self.redraw(True)
  1160.     
  1161.     self.valsLock.release()
  1162.   
  1163.   def redraw(self, forceRedraw=False, block=False):
  1164.     # determines if the content needs to be redrawn or not
  1165.     panel.Panel.redraw(self, forceRedraw, block)
  1166.   
  1167.   def run(self):
  1168.     """
  1169.     Redraws the display, coalescing updates if events are rapidly logged (for
  1170.     instance running at the DEBUG runlevel) while also being immediately
  1171.     responsive if additions are less frequent.
  1172.     """
  1173.     
  1174.     lastDay = daysSince() # used to determine if the date has changed
  1175.     while not self._halt:
  1176.       currentDay = daysSince()
  1177.       timeSinceReset = time.time() - self._lastUpdate
  1178.       maxLogUpdateRate = self._config["features.log.maxRefreshRate"] / 1000.0
  1179.       
  1180.       sleepTime = 0
  1181.       if (self.msgLog == self._lastLoggedEvents and lastDay == currentDay) or self.isPaused():
  1182.         sleepTime = 5
  1183.       elif timeSinceReset < maxLogUpdateRate:
  1184.         sleepTime = max(0.05, maxLogUpdateRate - timeSinceReset)
  1185.       
  1186.       if sleepTime:
  1187.         self._cond.acquire()
  1188.         if not self._halt: self._cond.wait(sleepTime)
  1189.         self._cond.release()
  1190.       else:
  1191.         lastDay = currentDay
  1192.         self.redraw(True)
  1193.         
  1194.         # makes sure that we register this as an update, otherwise lacking the
  1195.         # curses lock can cause a busy wait here
  1196.         self._lastUpdate = time.time()
  1197.   
  1198.   def stop(self):
  1199.     """
  1200.     Halts further resolutions and terminates the thread.
  1201.     """
  1202.     
  1203.     self._cond.acquire()
  1204.     self._halt = True
  1205.     self._cond.notifyAll()
  1206.     self._cond.release()
  1207.   
  1208.   def _resetListener(self, _, eventType):
  1209.     # if we're attaching to a new tor instance then clears the log and
  1210.     # prepopulates it with the content belonging to this instance
  1211.     
  1212.     if eventType == torTools.State.INIT:
  1213.       self.reprepopulateEvents()
  1214.       self.redraw(True)
  1215.   
  1216.   def _getTitle(self, width):
  1217.     """
  1218.     Provides the label used for the panel, looking like:
  1219.       Events (ARM NOTICE - ERR, BW - filter: prepopulate):
  1220.     
  1221.     This truncates the attributes (with an ellipse) if too long, and condenses
  1222.     runlevel ranges if there's three or more in a row (for instance ARM_INFO,
  1223.     ARM_NOTICE, and ARM_WARN becomes "ARM_INFO - WARN").
  1224.     
  1225.     Arguments:
  1226.       width - width constraint the label needs to fix in
  1227.     """
  1228.     
  1229.     # usually the attributes used to make the label are decently static, so
  1230.     # provide cached results if they're unchanged
  1231.     self.valsLock.acquire()
  1232.     currentPattern = self.regexFilter.pattern if self.regexFilter else None
  1233.     isUnchanged = self._titleArgs[0] == self.loggedEvents
  1234.     isUnchanged &= self._titleArgs[1] == currentPattern
  1235.     isUnchanged &= self._titleArgs[2] == width
  1236.     if isUnchanged:
  1237.       self.valsLock.release()
  1238.       return self._titleCache
  1239.     
  1240.     eventsList = list(self.loggedEvents)
  1241.     if not eventsList:
  1242.       if not currentPattern:
  1243.         panelLabel = "Events:"
  1244.       else:
  1245.         labelPattern = uiTools.cropStr(currentPattern, width - 18)
  1246.         panelLabel = "Events (filter: %s):" % labelPattern
  1247.     else:
  1248.       # does the following with all runlevel types (tor, arm, and torctl):
  1249.       # - pulls to the start of the list
  1250.       # - condenses range if there's three or more in a row (ex. "ARM_INFO - WARN")
  1251.       # - condense further if there's identical runlevel ranges for multiple
  1252.       #   types (ex. "NOTICE - ERR, ARM_NOTICE - ERR" becomes "TOR/ARM NOTICE - ERR")
  1253.       tmpRunlevels = [] # runlevels pulled from the list (just the runlevel part)
  1254.       runlevelRanges = [] # tuple of type, startLevel, endLevel for ranges to be consensed
  1255.       
  1256.       # reverses runlevels and types so they're appended in the right order
  1257.       reversedRunlevels = log.Runlevel.values()
  1258.       reversedRunlevels.reverse()
  1259.       for prefix in ("TORCTL_", "ARM_", ""):
  1260.         # blank ending runlevel forces the break condition to be reached at the end
  1261.         for runlevel in reversedRunlevels + [""]:
  1262.           eventType = prefix + runlevel
  1263.           if runlevel and eventType in eventsList:
  1264.             # runlevel event found, move to the tmp list
  1265.             eventsList.remove(eventType)
  1266.             tmpRunlevels.append(runlevel)
  1267.           elif tmpRunlevels:
  1268.             # adds all tmp list entries to the start of eventsList
  1269.             if len(tmpRunlevels) >= 3:
  1270.               # save condense sequential runlevels to be added later
  1271.               runlevelRanges.append((prefix, tmpRunlevels[-1], tmpRunlevels[0]))
  1272.             else:
  1273.               # adds runlevels individaully
  1274.               for tmpRunlevel in tmpRunlevels:
  1275.                 eventsList.insert(0, prefix + tmpRunlevel)
  1276.             
  1277.             tmpRunlevels = []
  1278.       
  1279.       # adds runlevel ranges, condensing if there's identical ranges
  1280.       for i in range(len(runlevelRanges)):
  1281.         if runlevelRanges[i]:
  1282.           prefix, startLevel, endLevel = runlevelRanges[i]
  1283.           
  1284.           # check for matching ranges
  1285.           matches = []
  1286.           for j in range(i + 1, len(runlevelRanges)):
  1287.             if runlevelRanges[j] and runlevelRanges[j][1] == startLevel and runlevelRanges[j][2] == endLevel:
  1288.               matches.append(runlevelRanges[j])
  1289.               runlevelRanges[j] = None
  1290.           
  1291.           if matches:
  1292.             # strips underscores and replaces empty entries with "TOR"
  1293.             prefixes = [entry[0] for entry in matches] + [prefix]
  1294.             for k in range(len(prefixes)):
  1295.               if prefixes[k] == "": prefixes[k] = "TOR"
  1296.               else: prefixes[k] = prefixes[k].replace("_", "")
  1297.             
  1298.             eventsList.insert(0, "%s %s - %s" % ("/".join(prefixes), startLevel, endLevel))
  1299.           else:
  1300.             eventsList.insert(0, "%s%s - %s" % (prefix, startLevel, endLevel))
  1301.       
  1302.       # truncates to use an ellipsis if too long, for instance:
  1303.       attrLabel = ", ".join(eventsList)
  1304.       if currentPattern: attrLabel += " - filter: %s" % currentPattern
  1305.       attrLabel = uiTools.cropStr(attrLabel, width - 10, 1)
  1306.       if attrLabel: attrLabel = " (%s)" % attrLabel
  1307.       panelLabel = "Events%s:" % attrLabel
  1308.     
  1309.     # cache results and return
  1310.     self._titleCache = panelLabel
  1311.     self._titleArgs = (list(self.loggedEvents), currentPattern, width)
  1312.     self.valsLock.release()
  1313.     return panelLabel
  1314.   
  1315.   def _trimEvents(self, eventListing):
  1316.     """
  1317.     Crops events that have either:
  1318.     - grown beyond the cache limit
  1319.     - outlived the configured log duration
  1320.     
  1321.     Argument:
  1322.       eventListing - listing of log entries
  1323.     """
  1324.     
  1325.     cacheSize = self._config["cache.logPanel.size"]
  1326.     if len(eventListing) > cacheSize: del eventListing[cacheSize:]
  1327.     
  1328.     logTTL = self._config["features.log.entryDuration"]
  1329.     if logTTL > 0:
  1330.       currentDay = daysSince()
  1331.       
  1332.       breakpoint = None # index at which to crop from
  1333.       for i in range(len(eventListing) - 1, -1, -1):
  1334.         daysSinceEvent = currentDay - daysSince(eventListing[i].timestamp)
  1335.         if daysSinceEvent > logTTL: breakpoint = i # older than the ttl
  1336.         else: break
  1337.       
  1338.       # removes entries older than the ttl
  1339.       if breakpoint != None: del eventListing[breakpoint:]
  1340.  
  1341.